package com.houdoudou.customer.buy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Customer;
import com.houdoudou.bean.Order;
import com.houdoudou.bean.Refund;
import com.houdoudou.customer.R;
import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.TransPasswordUtil;
import com.houdoudou.customer.common.UniversalHttpPost;
import com.houdoudou.customer.me.SetPaySecretAct;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Instrumentation;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class CreateRefundAct extends Activity {


	TextView orderId,orderMoney,orderState,title;
	EditText refundMoney,refondReason;
	LinearLayout  lt_refundType;
	Spinner sp_type;
	Button confirm;
	ProgressBar prgs;
	ImageButton back;
	JSONObject orderJO;
	String AFFAIR="";
	View.OnClickListener myOnClickListener;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_createrefund);
		init_listener();
		orderJO=JSONObject.fromObject(getIntent().getStringExtra("order"));
		AFFAIR=getIntent().getStringExtra("affair");
		orderId= (TextView) findViewById(R.id.tv_orderid_act_createrefund);
		orderMoney= (TextView) findViewById(R.id.tv_product_act_createrefund);
		orderState = (TextView) findViewById(R.id.tv_state_act_createrefund);
		back= (ImageButton) findViewById(R.id.imgbtn_back_act_choosepay);
		lt_refundType= (LinearLayout) findViewById(R.id.lt_refundtype_act_createrefund);
		
		confirm=  (Button) findViewById(R.id.btn_confirm_act_createrefund);
		refundMoney= (EditText) findViewById(R.id.et_refundmoney_act_createrefund);
		refondReason= (EditText) findViewById(R.id.et_reason_act_createrefund);
		sp_type= (Spinner) findViewById(R.id.sp_type_act_createrefund);
		title =  (TextView) findViewById(R.id.tv_title_act_createrefund);
		prgs= (ProgressBar) findViewById(R.id.prgs_act_createrefund);
		prgs.setVisibility(View.GONE);
		orderId.setText("订单号："+orderJO.getString(Order.ID));
		orderMoney.setText("总金额："+orderJO.getDouble(Order.MONEYCU)+"   总数量："+orderJO.getInt(Order.PRODUCTNUM));		
		orderState.setText("状态："+CommonFunction.spellOrderStateWord(orderJO.getInt(Order.STATE)));
		confirm.setOnClickListener(myOnClickListener);
		back.setOnClickListener(myOnClickListener);
		
		List<String> sp_refund= new ArrayList<String> ();  sp_refund.add(""); sp_refund.add("不想买了");  sp_refund.add("送货太迟");
		sp_refund.add("质量问题");
		ArrayAdapter<String>	adapter= new ArrayAdapter<String>(CreateRefundAct.this,android.R.layout.simple_spinner_item,sp_refund);
		sp_type.setAdapter(adapter);  
		if(AFFAIR.equals("createRefund")){ title.setText("申请退款"); confirm.setText("确认"); lt_refundType.setVisibility(View.VISIBLE); }
		if(AFFAIR.equals("updateRefund")){  title.setText("修改退款"); confirm.setText("修改"); lt_refundType.setVisibility(View.GONE);}
		
	}
	
private void init_listener(){
	myOnClickListener= new View.OnClickListener() {	
		@Override
		public void onClick(View v) {
		  
			if(v==confirm){
			double refundMoneyValue=-1;
			try {
				String refundMoneyStr= refundMoney.getText().toString();
				 refundMoneyValue=Double.parseDouble(refundMoneyStr);		
		                  	} catch (Exception e) {		
		   Toast.makeText(CreateRefundAct.this, "请输入合法的金额", Toast.LENGTH_SHORT).show(); 
		   return;}
			if( refundMoneyValue<=0|| refundMoneyValue> orderJO.getDouble(Order.MONEYCU)){
				 Toast.makeText(CreateRefundAct.this, "退款金额，必须在0和订单支付金额之间", Toast.LENGTH_SHORT).show(); 
			return;   }
		    if(sp_type.getSelectedItemPosition()==0&&AFFAIR.equals("createRefund")){
		    	Toast.makeText(CreateRefundAct.this, "请选择退款原因", Toast.LENGTH_SHORT).show(); 
				return;
		    }
			
			String[] params= new String[3];
            params[0]=Constant.BaseUrl+Constant.CustomerUrl;
            params[1]=AFFAIR; //PostCod
            JSONObject jsonData=new JSONObject();
            JSONObject customerJO= JSONObject.fromObject(Constant.customerJO);
            jsonData.put("customer", customerJO);
            JSONObject refundJO= new JSONObject();
            refundJO.put(Refund.ORDERID, orderJO.getLong(Order.ID));
            refundJO.put(Refund.MONEY, refundMoneyValue);
            if(AFFAIR.equals("createRefund")){
            refundJO.put(Refund.TYPE, sp_type.getSelectedItemPosition());}
            refundJO.put(Refund.REASON,refondReason.getText().toString());
            jsonData.put("refund",refundJO );
           params[2]=jsonData.toString();
           new HttpPostTaskforRefund().execute(params);
           prgs.setVisibility(View.VISIBLE);
			}
		if(v==back){
			new Thread () { 
				public void run () { 
				try { 
					
				Instrumentation inst= new Instrumentation(); 
				inst.sendKeyDownUpSync(KeyEvent. KEYCODE_BACK); 
				} catch(Exception e) { 
				e.printStackTrace(); 
				} 
				} 
				}.start();
		}	
			
		}};
}
	


private  class HttpPostTaskforRefund extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
		
			
			 System.out.println("-----------onPostExecute()--------------");
			 prgs.setVisibility(View.GONE);
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				 CommonFunction.alert(CreateRefundAct.this, "支付失败", "无网络连接");return;
		      
			}
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
			    JSONObject json = null;
			    int resultCode=-1;
				String resultInfo="";
				String affair="";				
				JSONObject jo;
				try{
			     json= JSONObject.fromObject(PostResult);
			     resultCode=json.getInt("resultCode");
			     resultInfo=json.getString("resultInfo");	
			     affair =json.getString("affair");	
			     jo= json.getJSONObject("jo");
				}catch(JSONException e){
					 CommonFunction.alert(CreateRefundAct.this, "失败", "数据解析错误");return;
				}
				 			   												      		       
		       if(resultCode==2||resultCode==3){ //表示回传了更新订单
		    	   JSONObject  orderJOOnline=jo.getJSONObject("order");		
		    	   Intent intent = new Intent(ChoosePayAct.ACTION_ORDER_CHANGED);  
				   intent.putExtra("order", orderJOOnline.toString());  
				   sendBroadcast(intent);   }
		       if(resultCode==2){ //成功
		    	   Toast.makeText(CreateRefundAct.this, "成功，即将跳转", Toast.LENGTH_SHORT).show();  
		    	   try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
		    	   CreateRefundAct.this.finish();
		       }
		       if(resultCode==1||resultCode==3){ //失败
		    	   CommonFunction.alert(CreateRefundAct.this, "失败", resultInfo); 
		       }  
			   
			   
			
		} //onPostExecute
	} //AsyncTask
	

}
